<?php

/**
 * 访客基本信息
 * File Name：GuestDataModel.php
 * File Encoding：UTF-8
 * File New Time：2014-8-11 15:00:15
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class GuestDataModel extends BaseModel {

    public function tableName() {
        return '{{guest_data}}';
    }

    public function rules() {
        return array(
            array('uid,isad,adname,session_id,mark_id,url,moule,controller,action,referer,root_domain,domain,browser,ip,query,agent,years,month,day,week,fewweeks,access_time,goods_id,cat_id', 'safe'),
        );
    }

    //数据保存前操作
    protected function beforeSave() {
        if ($this->isNewRecord) {
            $model = GuestRefererModel::model();
            $domain = $model->getDomain($this->referer);
            $this->root_domain = $domain['root_domain'];
            $this->domain = $domain['domain'];

            //广告跟踪
            $this->adname = GuestAdModel::model()->isAd($this->url);
            $key = 'guest_' . $this->mark_id;
            if (!empty($this->adname)) {
                $this->isad = 1;
                Yii::app()->cache->set($key, $this->adname, 300);
            } else {
                $isAd = Yii::app()->cache->get($key);
                if ($isAd) {
                    $this->isad = 1;
                    $this->adname = $isAd;
                    //更新
                    Yii::app()->cache->set($key, $isAd, 300);
                }
            }
        }
        return true;
    }

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * 返回当前用户标识
     * @return string 标识
     */
    public function getMarkId() {
        $cookie = Yii::app()->request->getCookies();
        if (empty($cookie['_guest'])) {
            $id = md5(GuestInfo::getAgent() . $this->getForwardedForIp());
            $cookie = new CHttpCookie('_guest', $id);
            $cookie->expire = time() + 60 * 60 * 24 * 30 * 12; //有限期
            Yii::app()->request->cookies['_guest'] = $cookie;
            return $id;
        } else {
            return $cookie['_guest']->value;
        }
    }

    /**
     * 返回用于当前用户，今天的用户标识
     * @return type
     */
    public function getDayMarkId() {
        $cookie = Yii::app()->request->getCookies();
        if (empty($cookie['_guestday'])) {
            $id = md5(GuestInfo::getAgent() . $this->getForwardedForIp());
            $cookie = new CHttpCookie('_guestday', $id);
            $jin = strtotime(date("Y-m-d 23:59:59")) - time();
            if ($jin < 0) {
                $jin = 0;
            }
            $cookie->expire = time() + (int) $jin; //有限期
            Yii::app()->request->cookies['_guestday'] = $cookie;
            return $id;
        } else {
            return $cookie['_guestday']->value;
        }
    }

    /**
     * 返回某个商品在一段时间内的点击数
     * @param type $goods_id 商品ID
     * @param type $start_time 开始时间
     * @param type $end_time 结束时间
     * @return type
     */
    public function getView($goods_id, $start_time, $end_time) {
        $where = array(
            'goods_id' => $goods_id,
            'access_time' => array(array('GT', $start_time), array('LT', $end_time), 'AND'),
        );
        return $this->count($this->where($where));
    }

    /**
     * 获取订单总数
     * @param type $goods_id
     * @param type $start_time
     * @param type $end_time
     * @return type
     */
    public function getTurnover($goods_id, $start_time, $end_time) {
        $where = array(
            'goods_id' => $goods_id,
            'orders_create_time' => array(array('GT', $start_time), array('LT', $end_time), 'AND'),
        );
        return SalesDataModel::model()->count($this->where($where));
    }

    /**
     * 获取订单官网数
     * @param type $goods_id
     * @param type $start_time
     * @param type $end_time
     * @return type
     */
    public function getTurnoverGuan($goods_id, $start_time, $end_time) {
        $where = array(
            'source' => 0,
            'goods_id' => $goods_id,
            'orders_create_time' => array(array('GT', $start_time), array('LT', $end_time), 'AND'),
        );
        return SalesDataModel::model()->count($this->where($where));
    }

    /**
     * 获取订单优站数
     * @param type $goods_id
     * @param type $start_time
     * @param type $end_time
     * @return type
     */
    public function getTurnoverYou($goods_id, $start_time, $end_time) {
        $where = array(
            'source' => 1,
            'goods_id' => $goods_id,
            'orders_create_time' => array(array('GT', $start_time), array('LT', $end_time), 'AND'),
        );
        return SalesDataModel::model()->count($this->where($where));
    }

    /**
     * 获取会员访问数
     * @param type $goods_id
     * @param type $start_time
     * @param type $end_time
     * @return type
     */
    public function getUserfanw($goods_id, $start_time, $end_time) {
        $where = array(
            'uid' => array('GT', 0),
            'goods_id' => $goods_id,
            'access_time' => array(array('GT', $start_time), array('LT', $end_time), 'AND'),
        );
        return $this->count($this->where($where));
    }

    /**
     * 获取游客访问数
     * @param type $goods_id
     * @param type $start_time
     * @param type $end_time
     * @return type
     */
    public function getYoukefanw($goods_id, $start_time, $end_time) {
        $where = array(
            'uid' => 0,
            'goods_id' => $goods_id,
            'access_time' => array(array('GT', $start_time), array('LT', $end_time), 'AND'),
        );
        return $this->count($this->where($where));
    }

    /**
     * 获取阿里云通过SLB负载均衡取得客户端IP
     * @return String ip地址
     */
    public function getForwardedForIp() {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR']) {
            $ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $ip = trim($ip[0]);
            return $ip ? $ip : '127.0.0.1';
        }
        return Yii::app()->request->userHostAddress;
    }

    //记录
    public function record() {
        if (in_array(ACTION_NAME, array('error')) || IS_AJAX || IS_POST) {
            return true;
        }
        $time = time();
        $data = array();
        $data['uid'] = Yii::app()->user->uid;
        $data['session_id'] = $this->getDayMarkId(); //Yii::app()->session->sessionID;
        $data['mark_id'] = $this->getMarkId();
        $data['url'] = Yii::app()->request->hostInfo . Yii::app()->request->getUrl();
        $data['moule'] = GROUP_NAME;
        $data['controller'] = CONTROLLER_NAME;
        $data['action'] = ACTION_NAME;
        $data['referer'] = GuestInfo::getReferer();
        $data['browser'] = GuestInfo::getBrowser();
        $data['ip'] = $this->getForwardedForIp();
        $data['query'] = GuestInfo::getQuery();
        $data['agent'] = GuestInfo::getAgent();
        $data['years'] = (int) date('Y', $time); //年
        $data['month'] = (int) date('m', $time); //月
        $data['day'] = (int) date('d', $time); //日
        $data['week'] = (int) date('w', $time); //星期 0（表示星期天）到 6（表示星期六）
        $data['fewweeks'] = (int) date('W', $time);
        $data['access_time'] = $time;
        $data['goods_id'] = (int) Yii::app()->request->getParam('gid');
        $data['cat_id'] = (int) Yii::app()->request->getParam('cid');
        //记录访客日志，调试模式下不记录
        if (defined('YII_DEBUG') && YII_DEBUG == false) {
            try {
                @RedisCluster::getInstance()->push('guest_record', $data);
            } catch (Exception $exc) {
                
            }
        }
    }

}
